package logic

import (
	"cart_srv/cart"
	"cart_srv/internal/svc"
	"cart_srv/models/mysql"
	"cart_srv/models/redis"
	"context"
	"errors"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	// todo: add your logic here and delete this line

	//判断商品是否存在
	g := mysql.Goods{}
	err := g.Show(int(in.GoodsId))
	if err != nil {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}

	// 获取库存
	stock := redis.GetGoodsStock(int(in.GoodsId))
	if stock < int64(in.Quantity) {
		return nil, errors.New("库存不足")
	}
	//判断购物车中是否有商品 从缓存中中匹配
	//如果有商品追加商品库存
	//没有则添加一条商品
	if redis.GetCartGoodsIsExists(int(in.UserId), int(in.GoodsId)) {

		quantity := in.Quantity
		err = redis.UpdateCartNum(int(in.UserId), int(in.GoodsId), int(quantity))
		if err != nil {
			return nil, errors.New("购物车商品数量追加失败")
		}
		fmt.Println("购物车商品数量追加成功")
	} else {
		m := make(map[string]interface{})
		m["userId"] = in.UserId
		m["goodsId"] = in.GoodsId
		m["quantity"] = in.Quantity
		m["goodsName"] = in.GoodsName
		m["goodsPrice"] = in.GoodsPrice

		err = redis.AddCart(int(in.UserId), int(in.GoodsId), m)
		fmt.Println("AddCart data:", m)
		if err != nil {
			return nil, errors.New("购物车收藏失败")
		}
		fmt.Println("购物车收藏成功(redis)")
	}
	return &cart.AddCartResponse{}, nil
}
